#include "musicprogressbar.h"

MusicProgressBar::MusicProgressBar(QWidget *parent) : QWidget(parent)
{
    setFixedHeight(12); // 进度条高度
}

// 传递媒体播放器
void MusicProgressBar::setMediaPlayer(QMediaPlayer *player)
{
    m_player = player;
    if (m_player)
    {
        // 关联播放器进度变化，更新进度条
        connect(m_player, &QMediaPlayer::positionChanged, this, [this]()
        {
            if (m_player->duration() > 0)
            {
                int progress = (m_player->position() * 100) / m_player->duration();
                m_progress = progress;
                update(); // 触发重绘
            }
        });
    }
}

void MusicProgressBar::setSliderPixmap(const QPixmap &pixmap)
{
    // 强制缩放到 20×20 像素
    this->m_sliderPix = pixmap.scaled(10, 10, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    update(); // 图标变化后重绘
}



void MusicProgressBar::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // ========== 1. 绘制进度条背景（渐变+圆角） ==========
    QLinearGradient bgGradient(0, 0, 0, height());
    bgGradient.setColorAt(0, QColor(230, 230, 230));
    bgGradient.setColorAt(1, QColor(200, 200, 200));
    painter.setBrush(bgGradient);
    painter.setPen(Qt::NoPen); // 取消边框
    painter.drawRoundedRect(0, 0, width(), height(), 6, 6); // 圆角半径6

    // ========== 2. 绘制已播放部分（渐变+圆角） ==========
    if (m_progress > 0) {
        QLinearGradient filledGradient(0, 0, 0, height());
        filledGradient.setColorAt(0, QColor(255, 69, 0)); // 橙色渐变
        filledGradient.setColorAt(1, QColor(255, 140, 0));
        painter.setBrush(filledGradient);
        painter.drawRoundedRect(0, 0, width() * m_progress / 100.0, height(), 6, 6);
    }

    // ========== 3. 绘制滑块（精致图标） ==========
    if (!m_sliderPix.isNull()) {
        int sliderW = m_sliderPix.width();
        int sliderH = m_sliderPix.height();
        int sliderX = (width() * m_progress / 100.0) - sliderW / 2;
        sliderX = qBound(0, sliderX, width() - sliderW);
        int sliderY = (height() - sliderH) / 2;
        painter.drawPixmap(sliderX, sliderY, m_sliderPix);
    }
}



void MusicProgressBar::mousePressEvent(QMouseEvent *event)
{
    if (m_player && event->button() == Qt::LeftButton) {
        m_isDragging = true; // 标记为“正在拖动”
        updateProgressFromMouse(event->x());
    }
}

void MusicProgressBar::mouseMoveEvent(QMouseEvent *event)
{
    if (m_isDragging && m_player) {
        updateProgressFromMouse(event->x());
    }
}

void MusicProgressBar::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    m_isDragging = false; // 拖动结束
}

// 从鼠标X坐标更新进度
void MusicProgressBar::updateProgressFromMouse(int x)
{
    int progress = (x * 100) / width();
    m_progress = progress;
    update();
    if (m_player->duration() > 0)
    {
        qint64 pos = (m_player->duration() * progress) / 100;
        m_player->setPosition(pos);
        emit progressChanged(progress);
    }
}

